import axios from '@/request'

// 基础查询接口
export const anomalyApi = {
  // 汇总查询
  summary: (params) => axios.post('/anomaly-query/summary', params),
  
  // 数据查询
  data: (params) => axios.post('/anomaly-query/data', params),
  
  // 原始数据查询
  rawData: (params) => axios.post('/anomaly-query/raw-data', params),
  
  // 导出查询结果
  export: (params, exportType) => axios.post(`/anomaly-query/export?exportType=${exportType}`, params),
  
  // 获取可用的分组维度
  getGroupDimensions: (queryType) => axios.get(`/anomaly-query/group-dimensions?queryType=${queryType}`),
  
  // 获取可用的输出字段
  getOutputFields: (queryType) => axios.get(`/anomaly-query/output-fields?queryType=${queryType}`)
}

// 数据预测接口
export const predictionApi = {
  // 总金额预测 - 基于ARIMA模型
  totalAmountPrediction: (params) => axios.post('/anomaly-query/prediction/total-amount', params),
  
  // 分组预测 - 基于ARIMA模型
  groupedPrediction: (params) => axios.post('/anomaly-query/prediction/grouped', params)
}

// 异动监测接口
export const monitoringApi = {
  // 重点商品监测
  keyCommodity: (params) => axios.post('/anomaly-query/monitoring/key-commodity', params),
  
  // 口岸异动监测
  port: (params) => axios.post('/anomaly-query/monitoring/port', params),
  
  // 重点业态监测
  businessType: (params) => axios.post('/anomaly-query/monitoring/business-type', params),
  
  // 地区监测
  region: (params) => axios.post('/anomaly-query/monitoring/region', params),
  
  // 国别监测
  country: (params) => axios.post('/anomaly-query/monitoring/country', params)
}

// 钻取分析接口
export const drillDownApi = {
  // 钻取分析
  analysis: (params) => axios.post('/anomaly-query/drill-down', params)
}

// 二级封装 - 业务逻辑封装
export const anomalyService = {
  // 获取监测数据
  async getMonitoringData(type, params = {}) {
    try {
      let response
      switch (type) {
        case 'country':
          response = await monitoringApi.country(params)
          break
        case 'port':
          response = await monitoringApi.port(params)
          break
        case 'businessType':
          response = await monitoringApi.businessType(params)
          break
        case 'region':
          response = await monitoringApi.region(params)
          break
        default:
          throw new Error('不支持的监测类型')
      }
      
      if (response.data && response.data.success) {
        // 确保返回数组格式
        let data = response.data.data
        if (Array.isArray(data)) {
          // 如果直接是数组，使用数组
          data = data
        } else if (typeof data === 'object' && data !== null) {
          // 如果是对象，尝试转换为数组
          if (Object.keys(data).length === 0) {
            data = []
          } else {
            // 尝试从对象中提取数组数据
            data = Object.values(data).find(val => Array.isArray(val)) || []
          }
        } else {
          data = []
        }
        
        return {
          success: true,
          data: data,
          message: response.data.message
        }
      } else {
        return {
          success: false,
          data: [],
          message: response.data?.message || '查询失败'
        }
      }
    } catch (error) {
      return {
        success: false,
        data: [],
        message: error.message || '请求失败'
      }
    }
  },

  // 获取预测数据
  async getPredictionData(type, params = {}) {
    try {
      let response
      switch (type) {
        case 'total':
          response = await predictionApi.totalAmountPrediction(params)
          break
        case 'grouped':
          response = await predictionApi.groupedPrediction(params)
          break
        default:
          throw new Error('不支持的预测类型')
      }
      
      console.log('API原始响应:', response) // 调试日志
      
      if (response.data && response.data.success) {
        // 从后端返回的数据中提取tableData
        let data = response.data.data
        console.log('API返回的data字段:', data) // 调试日志
        
        if (data && data.tableData && Array.isArray(data.tableData)) {
          // 如果有tableData字段，直接使用
          console.log('找到tableData，长度:', data.tableData.length) // 调试日志
          data = data.tableData
        } else if (Array.isArray(data)) {
          // 如果直接是数组，使用数组
          console.log('data是数组，长度:', data.length) // 调试日志
          data = data
        } else if (typeof data === 'object' && data !== null) {
          // 如果是对象，尝试转换为数组
          console.log('data是对象，尝试转换') // 调试日志
          if (Object.keys(data).length === 0) {
            data = []
          } else {
            // 尝试从对象中提取数组数据
            const arrayValues = Object.values(data).filter(val => Array.isArray(val))
            if (arrayValues.length > 0) {
              data = arrayValues[0]
              console.log('从对象中提取到数组，长度:', data.length) // 调试日志
            } else {
              data = []
              console.log('对象中没有找到数组数据') // 调试日志
            }
          }
        } else {
          data = []
          console.log('data为空或无效') // 调试日志
        }
        
        console.log('最终返回的数据:', data) // 调试日志
        
        return {
          success: true,
          data: data,
          message: response.data.message
        }
      } else {
        console.log('API调用失败:', response.data) // 调试日志
        return {
          success: false,
          data: [],
          message: response.data?.message || '预测失败'
        }
      }
    } catch (error) {
      console.error('API调用异常:', error) // 调试日志
      return {
        success: false,
        data: [],
        message: error.message || '请求失败'
      }
    }
  },

  // 获取钻取分析数据
  async getDrillDownData(params) {
    try {
      const response = await drillDownApi.analysis(params)
      
      if (response.data && response.data.success) {
        // 确保返回数组格式
        let data = response.data.data
        if (!Array.isArray(data)) {
          data = []
        }
        
        return {
          success: true,
          data: data,
          message: response.data.message
        }
      } else {
        return {
          success: false,
          data: [],
          message: response.data?.message || '钻取分析失败'
        }
      }
    } catch (error) {
      return {
        success: false,
        data: [],
        message: error.message || '请求失败'
      }
    }
  },

  // 获取基础查询数据
  async getQueryData(type, params = {}) {
    try {
      let response
      switch (type) {
        case 'summary':
          response = await anomalyApi.summary(params)
          break
        case 'data':
          response = await anomalyApi.data(params)
          break
        case 'raw':
          response = await anomalyApi.rawData(params)
          break
        default:
          throw new Error('不支持的查询类型')
      }
      
      if (response.data && response.data.success) {
        // 确保返回数组格式
        let data = response.data.data
        if (!Array.isArray(data)) {
          data = []
        }
        
        return {
          success: true,
          data: data,
          message: response.data.message
        }
      } else {
        return {
          success: false,
          data: [],
          message: response.data?.message || '查询失败'
        }
      }
    } catch (error) {
      return {
        success: false,
        data: [],
        message: error.message || '请求失败'
      }
    }
  }
} 